// pages/attractionsOrder/attractionsOrder.js
const app = getApp()
Page({
  data: {
    spotId:"",
    ticketId:"",
    attraction: {
      imageUrl:"https://img-u-0.51miz.com/Templet/00/16/62/17/166217_f018fbf00e8f4091d48fee5049370245.jpg-0.jpg",
      name:"北京环球度假区",
      rating: 4.6,
      reviewCount: 3.4,
    },
    todayDate: '', // 动态计算
    price: 500,
    tomorrowDate: '', // 动态计算
    dayAfterTomorrowDate: '', // 动态计算
    selectedDate: '', 
    isDatePickerVisible: false, // 控制日期选择器是否显示
    minDate: new Date().getTime(), // 最小日期为今天
    maxDate: new Date(2025, 11, 31).getTime(), // 最大日期可设为2025年底

    passengers: [],
    ticketQuantity: 1,
    ticketPrice:0,
    ticketType:"",
    ticketTitle:"",
    ticketNum:0,
    totalNum:1,
    totalPrice: 0,
   
  },
  // 接收从选择出行人页面传来的数据
  updatePassengers(newPassengers) {
    this.setData({
      passengers: [...this.data.passengers, ...newPassengers]
    });
  },
  choosePassengers(){
    wx.navigateTo({
      url: '/pages/attractionsChoosePeople/attractionsChoosePeople',
    })
  },
  onClickLeft(){
    wx.navigateBack();
  },
  onLoad(options) {
    if(options && options.spotId && options.ticketId){
      const Id = options.spotId
      const ticketId = options.ticketId
        this.setData({
          spotId:Id,
          ticketId:ticketId
        })
        this.loadAttractions(Id)
    }
    // console.log("spotId",this.data.spotId)
    // console.log("ticketId",this.data.ticketId)
    
    this.updateDynamicDates();
  },

  onShow(){
    this.getTicketPrice()
  },

  loadAttractions(Id){
      wx.request({
        url: `http://localhost:8080/system/spot/${Id}`,
        header: {
          Authorization: app.globalData.token
        },
        success: (res) => {
          if (res.data.code === 200 && res.data.data) {
            const spot = res.data.data;
            const baseUrl = 'http://localhost:8080';
        
            // 构造 attraction 对象
            const attraction = {
              imageUrl: baseUrl + spot.imgUrl,       // 拼接图片路径
              name: spot.name,                       // 景点名称
              rating: spot.star,                     // 评分
              reviewCount: spot.commentCount || 0,    // 评论数量
            };
        
            // 更新页面数据
            this.setData({
              attraction: attraction,
              price: spot.min_price                  // 设置默认价格用于预订
            });
          } else {
            wx.showToast({ title: '加载景点失败', icon: 'none' });
          }
        }
      })
  },

  getTicketPrice(){
    wx.request({
      url: `http://localhost:8080/system/ticket/${this.data.ticketId}`,
      header: {
        Authorization: app.globalData.token
      },
      success:(res)=>{
        // console.log(res)
        if(res.data.code === 200){
          this.setData({
            ticketPrice:res.data.data.price * 100,
            totalPrice:res.data.data.price * 100,
            ticketType:res.data.data.name,
            ticketTitle:res.data.data.title
          })
          if(this.data.ticketType === "套票"){
              this.setData({
                ticketNum:2,
                totalNum:2
              })
          }else{
            this.setData({
              ticketNum:1,
              totalNum:1,
            })
          }
        }
      }
    })
    
  },

  updateDynamicDates() {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    const dayAfterTomorrow = new Date(today);
    dayAfterTomorrow.setDate(today.getDate() + 2);


  // 格式化日期为 "YYYY-M-D"
  const format_date = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

    this.setData({
      todayDate: format_date(today),
      tomorrowDate: format_date(tomorrow),
      dayAfterTomorrowDate: format_date(dayAfterTomorrow)
    });

  },

  selectDate(e) {
    const date = e.currentTarget.dataset.date;
    if(date == "today"){
      const tmpdate = this.data.todayDate
      this.setData({ selectedDate: tmpdate });
    }
    if(date == "tomorrow"){
      const tmpdate = this.data.tomorrowDate
      this.setData({ selectedDate: tmpdate });
    }
    if(date == "dayAfterTomorrow"){
      const tmpdate = this.data.dayAfterTomorrowDate
      console.log(tmpdate)
      this.setData({ selectedDate: tmpdate });
    }
  },

   // 打开日历
   openDatePicker() {
    this.setData({ isDatePickerVisible: true });
  },

  // 确认选择日期
  onDateConfirm(e) {
    const date = e.detail; // 获取选中日期对象

    // 补零函数
    const padZero = (num) => num < 10 ? `0${num}` : num;

    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1); // 月份从 0 开始
    const day = padZero(date.getDate());

    const formattedDate = `${year}-${month}-${day}`;

    this.setData({
      selectedDate: formattedDate, // 设置为带前导零的日期
      isDatePickerVisible: false
    });
  },


  // 取消选择日期
  onDateCancel() {
    this.setData({ isDatePickerVisible: false });
  },

 // 删除乘客
 removePassenger(e) {
  const index = e.currentTarget.dataset.index;
  const passengers = this.data.passengers;
  
  // 创建动画
  const animation = wx.createAnimation({
    duration: 300,
    timingFunction: 'ease-out'
  });
  
  animation.scale(0.8).opacity(0).translateX(100).step();
  
  // 更新数据并添加动画
  passengers[index].animation = animation.export();
  this.setData({ passengers });
  
  // 延迟删除
  setTimeout(() => {
    passengers.splice(index, 1);
    this.setData({ passengers });
  }, 300);
},

  // 增加购票数量
  increaseQuantity() {
    let quantity = this.data.ticketQuantity;
    quantity++;
    this.setData({ ticketQuantity: quantity });
    console.log(quantity)
    this.setData({totalNum:quantity * this.data.ticketNum})
    this.updateTotalPrice(quantity); // 更新总价
  },

  // 减少购票数量
  decreaseQuantity() {
    let quantity = this.data.ticketQuantity;
    if (quantity > 1) {
      quantity--;
      this.setData({ ticketQuantity: quantity });
      this.setData({totalNum:quantity * this.data.ticketNum})
      this.updateTotalPrice(quantity); // 更新总价
    }
  },
  updateTotalPrice(quantity){
      const price = quantity * this.data.ticketPrice;
      this.setData({
        totalPrice:price
      })
  },
  onSubmit() {
    const { passengers, totalNum ,selectedDate} = this.data;
    console.log("totalNum",totalNum)
    // 判断游客人数是否匹配 totalNum
    if (passengers.length !== totalNum) {
      if(this.data.ticketNum == 2){
        wx.showToast({
          title: '您当前购买的为套票，每张门票可选择两位游客',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      wx.showToast({
        title: '请确认游客人数与购票数量一致',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    if(selectedDate == ''){
      wx.showToast({
        title: '请选择游玩日期',
        icon: 'none',
        duration: 2000
      });
      return;
    }
  
    // 校验通过后跳转到支付页面或其他操作
    wx.navigateTo({
      url: `/pages/attractionsPaid/attractionsPaid?Id=${this.data.spotId}&num=${this.data.totalNum / this.data.ticketNum}&price=${this.data.totalPrice}&selectedDate=${this.data.selectedDate}&ticketId=${this.data.ticketId}`,
    });
  }

  
});
